package com.googlecode.cswish.util;

import java.io.Reader;
import java.io.StringReader;
import java.util.HashMap;

import org.apache.log4j.Logger;
import org.springframework.ui.freemarker.FreeMarkerTemplateUtils;

import freemarker.template.Template;
import freemarker.template.TemplateModel;

/**
 * Rule expression engine
 * 
 * @author Jerry.Feng Date: 2008-6-6
 */
public class FreemarkerTemplateEngine {
	
	private static final Logger logger = Logger.getLogger(FreemarkerTemplateEngine.class);
	
	private static final FreemarkerTemplateEngine instance = new FreemarkerTemplateEngine();
	
	private final HashMap<String, Template> templates = new HashMap<String, Template>();

	public static FreemarkerTemplateEngine getInstance() {
		return instance;
	}
	
	public void register(String name, String content) {
		Template template = templates.get(content);
		if (template != null) {
			return;
		}
		
		Reader reader = new StringReader(content);
		try {
			template = new Template(name, reader, null);
			templates.put(content, template);
		} catch (Exception ex) {
			logger.error(ex);
		}
	}
	
	public String execute(String content, TemplateModel model) {
		Template template = templates.get(content);
		if (template == null) {
			logger.warn("Can't find template:" + content);
		} else {
			try {
				return FreeMarkerTemplateUtils.processTemplateIntoString(template, model);
			} catch (Exception ex) {
				logger.debug(ex);
			}
		}
		return "false";
	}
}